
package com.zeroes.cons;



import java.util.concurrent.atomic.AtomicBoolean;

import android.util.Log;

public class GameLoop implements Runnable {
  private static final boolean LOG_FPS = true;
  private static final int MAX_DELTA = 100;

  private AtomicBoolean running = new AtomicBoolean();
 // private AndroidGraphics gfx;

  private long timeOffset = System.currentTimeMillis();

  private int updateRate;
  private float accum;
  private int lastTime;

  private float totalTime;
  private int framesPainted;

  public GameLoop() {
   // gfx = AndroidPlatform.instance.graphics();
  }

  public void start() {
    if (!running.get()) {

      this.updateRate = ZSGameManager.AskMe().getupdaterateforcurrentGame();
      running.set(true);
    }
  }

  public void pause() {

    running.set(false);
  }
  
  public void resume() {

	    running.set(true);
	  }

  @Override
  public void run() {
    // The thread can be stopped between runs.
    if (!running.get())
      return;

    int now = time();
    float delta = now - lastTime;
    if (delta > MAX_DELTA)
      delta = MAX_DELTA;
    lastTime = now;

    if (updateRate == 0) {
      //AndroidPlatform.instance.update(delta);
      ZSGameManager.AskMe().updateGameLogic(delta);
    	accum = 0;
    } else {
      accum += delta;
      while (accum >= updateRate) {
       // AndroidPlatform.instance.update(updateRate);
    	  ZSGameManager.AskMe().updateGameLogic(updateRate);
        accum -= updateRate;
      }
    }

    paint((updateRate == 0) ? 0 : accum / updateRate);
   // Log.d("ConstructoidActivity", "update rate "+updateRate);
    if (LOG_FPS) {
      totalTime += delta / 1000;
      framesPainted++;
      if (totalTime > 1) {
      //  log().info("FPS: " + framesPainted / totalTime);
    	//  Log.v("gtrans", "FPS: " + framesPainted / totalTime);
    	  ZSGameManager.AskMe().FrameRate(framesPainted / totalTime);
        totalTime = framesPainted = 0;
      }
    }
  }

  private int time() {
    // System.nanoTime() would be better here, but it's busted on the HTC EVO
    // 2.3 update. Instead we use an offset from a known time to keep it within
    // int range.
	  
    return (int) (System.currentTimeMillis() - timeOffset);
	 // return (int)(System.nanoTime() - timeOffset)/1000000 ;
  }

  public boolean running() {
    return running.get();
  }

  protected void paint(float paintAlpha) {
  //  gfx.preparePaint();
   // AndroidPlatform.instance.game.paint(paintAlpha); // Run the game's custom painting code
	  ZSGameManager.AskMe().tick(paintAlpha);
	  //  gfx.paintLayers(); // Paint the scene graph
  }
}
